//
//  HomeViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/18.
//

#import "HomeViewController.h"
#import "HomeThreeBtnTableCell.h"
#import "HomeBannerTableCell.h"
#import "HomeQuicklyWayTableCell.h"
#import "HomeContactServiceTableCell.h"
#import "HomeListTableCell.h"
#import "HomeRepaymentTableCell.h"
#import "EmptyTableViewCell.h"

#import "QuestionListViewController.h"
#import "OrderDetailViewController.h"

#define kHomeThreeBtnCell    @"kHomeThreeBtnCell"
#define kHomeBannerCell      @"kHomeBannerCell"
#define kHomeQuicklyCell     @"kHomeQuicklyCell"
#define kHomeServiceCell     @"kHomeServiceCell"
#define kHomeListCell        @"kHomeListCell"
#define kHomeRepayCell       @"kHomeRepayCell"
#define kErrorNetCell        @"kErrorNetCell"

@interface HomeViewController ()<CLLocationManagerDelegate>

@property (nonatomic) BOOL isNetworkError;
@property (nonatomic) NSInteger recorNoNetworkTimes;

@property (nonatomic) BOOL isOffsetY,isSmallCard;

@property (nonatomic) UIView *headView;

@property (nonatomic) HomeModel *hModel;
@property (nonatomic) LargeSmallCardModel *cardModel;

@property (nonatomic) NSMutableArray *repayArr,*listArr,*bannerArr;

@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) NSTimer *maiDianTimer;
@property (nonatomic) NSInteger timeInt;
@property (nonatomic) BOOL isLocationSuccess;

@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 1 || status == 2){
            self.isNetworkError = NO;
            if (self.recorNoNetworkTimes == 1) {
                [self loadData];
            }
            self.recorNoNetworkTimes = 0;
        }
        else{
            self.isNetworkError = YES;
            self.recorNoNetworkTimes = 1;
            self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(180))];
            [self.data removeAllObjects];
        }
        [self.tableView reloadData];
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [self loadData];
    
}

- (void)viewDidLoad {
    self.isTableViewStyleGrouped = YES;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.repayArr = [[NSMutableArray alloc] init];
    self.listArr = [[NSMutableArray alloc] init];
    self.bannerArr = [[NSMutableArray alloc] init];
    
    [self.tableView registerClass:[HomeThreeBtnTableCell class] forCellReuseIdentifier:kHomeThreeBtnCell];
    [self.tableView registerClass:[HomeBannerTableCell class] forCellReuseIdentifier:kHomeBannerCell];
    [self.tableView registerClass:[HomeQuicklyWayTableCell class] forCellReuseIdentifier:kHomeQuicklyCell];
    [self.tableView registerClass:[HomeContactServiceTableCell class] forCellReuseIdentifier:kHomeServiceCell];
    [self.tableView registerClass:[HomeRepaymentTableCell class] forCellReuseIdentifier:kHomeRepayCell];
    [self.tableView registerClass:[HomeListTableCell class] forCellReuseIdentifier:kHomeListCell];
    
    [self.tableView registerClass:[EmptyTableViewCell class] forCellReuseIdentifier:kErrorNetCell];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:kNotificationLoginSucess object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeNoti) name:kNotificationLogoutSucess object:nil];
    
    
    [DataCategoryUpload uploadDataIDFA:NO];
    
    
}

- (void)removeNoti{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationLoginSucess object:nil];
}

- (void)loadData{
    if (self.isNetworkError) {
        return;
    }
    [BoxLoadingHelper showBoxLoadingWithMessage:@"" onView:self.view withOriginY:0];
    NSMutableDictionary *muDic = @{
        @"home":@"homeString",
    }.mutableCopy;
    [HttpNetHelper getNetworkHelperForPath:kHomeUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        [self.data removeAllObjects];
        
        NSDictionary *dic = responseDic[@"clip"];
        self.hModel = [HomeModel mj_objectWithKeyValues:dic];
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kIsNeedLocation];
        if ([[CurrentUser mine] isYNLanguage]) {
            [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:kIsNeedLocation];
        }
        else{
            [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:kIsNeedLocation];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
        
        [self initHeadView];
        
        [self initDataDic];
        
        self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
    } withIsForm:YES];
    
}



- (void)initDataDic{
    
    [self.repayArr removeAllObjects];
    [self.listArr removeAllObjects];
    [self.bannerArr removeAllObjects];
    
    BOOL isShowBanner = NO;
    NSMutableArray *muArr = [[NSMutableArray alloc] init];
    for (int i=0; i<self.hModel.continuing.count; i++) {
        NSDictionary *dic = self.hModel.continuing[i];
        if ([dic[@"lord"] isEqualToString:kChopped]) {
            isShowBanner = YES;
            [muArr addObjectsFromArray:dic[@"soldier"]];
            break;
        }
    }
  
    NSMutableArray *titleArr = [[NSMutableArray alloc] init];
    for (int i=0; i<muArr.count; i++) {
        BannerModel *mm = [BannerModel mj_objectWithKeyValues:muArr[i]];
        [titleArr addObject:mm.practical];
        [titleArr addObject:mm.arrow];
    }
    
     
    for (int i = 0; i < titleArr.count; i += 4) {
        NSRange range = NSMakeRange(i, MIN(4, titleArr.count - i));
        [self.bannerArr addObject:[titleArr subarrayWithRange:range]];
    }

   

    
    BOOL isShowRepay = NO;
    for (int i=0; i<self.hModel.continuing.count; i++) {
        NSDictionary *dic = self.hModel.continuing[i];
        if ([dic[@"lord"] isEqualToString:kThat]) {
            isShowRepay = YES;
            [self.repayArr addObjectsFromArray:dic[@"soldier"]];
            break;
        }
    }
    BOOL isShowList = NO;
    for (int i=0; i<self.hModel.continuing.count; i++) {
        NSDictionary *dic = self.hModel.continuing[i];
        if ([dic[@"lord"] isEqualToString:kSent]) {
            isShowList = YES;
            self.listArr = [ProductListModel mj_objectArrayWithKeyValuesArray:dic[@"soldier"]];
            break;
        }
    }
    

    NSDictionary *dic1 = @{
                           @"title" : @"",
                           @"selSec" : @"",
                           @"class" : [HomeThreeBtnTableCell class],
                           @"value" : @"",
                           @"sel" : @"",
                           };
    
    NSDictionary *dic2 = @{
                           @"title" : @"",
                           @"selSec" : @"",
                           @"class" : [HomeBannerTableCell class],
                           @"value" : @"",
                           @"sel" : @"",
                           };
    
    NSDictionary *dic3 = @{
                           @"title" : @"",
                           @"selSec" : @"",
                           @"class" : [HomeQuicklyWayTableCell class],
                           @"value" : @"",
                           @"sel" : @"",
                           };
    
    NSDictionary *dic4 = @{
                           @"title" : @"",
                           @"selSec" : @"",
                           @"class" : [HomeContactServiceTableCell class],
                           @"value" : @"",
                           @"sel" : @"",
                           };
    
    NSDictionary *dic5 = @{
                           @"title" : @"",
                           @"selSec" : @"",
                           @"class" : [HomeRepaymentTableCell class],
                           @"value" : @"",
                           @"sel" : @"",
                           };
    
    NSDictionary *dic6 = @{
                           @"title" : @"",
                           @"selSec" : @"",
                           @"class" : [HomeListTableCell class],
                           @"value" : self.listArr.count ? self.listArr : @"",
                           @"sel" : @"",
                           };
    
    
    if (![CurrentUser mine].isYNLanguage) {
        [self.data addObject:dic1];
        if (isShowBanner) {
            [self.data addObject:dic2];
        }
       
    }
    
    
    if (!self.isSmallCard) {
        [self.data addObject:dic3];
        [self.data addObject:dic4];
    }
    
    
    if (isShowRepay) {
        [self.data addObject:dic5];
    }
    if (isShowList) {
        [self.data addObject:dic6];
    }
    
    

    [self.tableView reloadData];
    
}

- (void)initHeadView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.001f)];
    self.tableView.tableHeaderView = headView;
    self.headView = headView;


    BOOL isSmallCard = NO;
    NSArray *cardArr = nil;
    for (int i=0; i<self.hModel.continuing.count; i++) {
        NSDictionary *dic = self.hModel.continuing[i];
        if ([dic[@"lord"] isEqualToString:kDirty] || [dic[@"lord"] isEqualToString:kCertainly]) {
            
            cardArr = dic[@"soldier"];
            if ([dic[@"lord"] isEqualToString:kDirty]) {
                isSmallCard = YES;
            }
            
            break;
        }
    }
    
    self.isSmallCard = isSmallCard;
    
    if (cardArr.count > 0) {
        self.cardModel = [LargeSmallCardModel mj_objectWithKeyValues:cardArr.firstObject];
    }
    
    headView.backgroundColor =  [UIColor redColor];
    
    headView.frame = CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(409));
    if (isSmallCard) {
        headView.frame = CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(93+283));
    }
    
    UIImageView *topImgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(177))];
    topImgV.image = [UIImage imageNamed:@"icon_home1"];
    [headView addSubview:topImgV];
    
    UIView *whiteV = [[UIView alloc] init];
    whiteV.frame = CGRectMake(0, DimensionBaseIphone6(164), kScreenWidth, DimensionBaseIphone6(245));
    if (isSmallCard) {
        whiteV.frame = CGRectMake(0, DimensionBaseIphone6(164), kScreenWidth, DimensionBaseIphone6(212));
    }
    whiteV.backgroundColor = kTableViewBackColor;
    [headView addSubview:whiteV];
    whiteV.layer.mask = [NSString UIBezierPathWithRect:whiteV.bounds withCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadiu:CGSizeMake(10, 10)];
    
    UIImageView *midImgV = [[UIImageView alloc] init];

    midImgV.frame = CGRectMake(15, 0, kScreenWidth - 30, DimensionBaseIphone6(409));
    midImgV.image = [UIImage imageNamed:@"icon_home2"];
    if (isSmallCard) {
        midImgV.frame = CGRectMake(15, DimensionBaseIphone6(93), kScreenWidth - 30, DimensionBaseIphone6(283));
        midImgV.image = [UIImage imageNamed:@"icon_home2-2"];
    }
    
    
    [headView addSubview:midImgV];
    
    midImgV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapMid = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLoan)];
    [midImgV addGestureRecognizer:tapMid];
    
    
    
    //data
    UIImageView *smImgV = [[UIImageView alloc] initWithFrame:CGRectMake(20, DimensionBaseIphone6(140), DimensionBaseIphone6(28), DimensionBaseIphone6(28))];
    if (isSmallCard) {
        smImgV.frame = CGRectMake(20, DimensionBaseIphone6(15), DimensionBaseIphone6(28), DimensionBaseIphone6(28));
    }
    smImgV.image = [UIImage imageNamed:@"icon_home4"];
    [midImgV addSubview:smImgV];
    
    UILabel *lab1 = [UILabel createLabel:[UIFont fontWithName:kFutura size:16] color:kBlackColor];
    lab1.text = esString(self.cardModel.caulfeild);
    lab1.frame = CGRectMake(smImgV.right + 5, 0, 200, 25);
    lab1.centerY = smImgV.centerY;
    [midImgV addSubview:lab1];
    
    UIImageView *dkImgV = [[UIImageView alloc] init];
    dkImgV.frame = CGRectMake(headView.width - 35 - 74, DimensionBaseIphone6(97), 74, DimensionBaseIphone6(162));
    if (isSmallCard) {
        dkImgV.frame = CGRectMake(headView.width - 35 - 74, DimensionBaseIphone6(64), 74, DimensionBaseIphone6(162));
    }
    dkImgV.image = [UIImage imageNamed:@"icon_home3"];
    [headView addSubview:dkImgV];
    
    UILabel *priceLab = [UILabel createLabel:[UIFont fontWithName:kFuturaBold size:44] color:kButtonDefaultColor];
    priceLab.frame = CGRectMake(20, smImgV.bottom + DimensionBaseIphone6(18), midImgV.width - 20 - 20, DimensionBaseIphone6(44));
    [midImgV addSubview:priceLab];
    priceLab.text = esString(self.cardModel.ugly);
    
    UILabel *priceLabDesc = [UILabel createLabel:[UIFont fontWithName:kFutura size:14] color:kBlackColor];
    priceLabDesc.frame = CGRectMake(20, priceLab.bottom + DimensionBaseIphone6(10), midImgV.width - 20 - 20 - 74 - 10, DimensionBaseIphone6(15));
    [midImgV addSubview:priceLabDesc];
    priceLabDesc.text = ASLocalizedString(@"home1Str");
    
    UILabel *rateLab = [UILabel createLabel:[UIFont fontWithName:kFutura size:15] color:[UIColor colorWithHexString:@"#FFFFFF"]];
    rateLab.frame = CGRectMake(20, priceLabDesc.bottom + DimensionBaseIphone6(30), 160, DimensionBaseIphone6(18));
    [midImgV addSubview:rateLab];
    rateLab.text = esString(self.cardModel.toiling);
    
    UILabel *rateLabDesc = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#75FA8D"]];
    rateLabDesc.frame = CGRectMake(20, rateLab.bottom + DimensionBaseIphone6(5), 160, DimensionBaseIphone6(16));
    [midImgV addSubview:rateLabDesc];
    rateLabDesc.text = ASLocalizedString(@"home2Str");
    
    UILabel *termLab = [UILabel createLabel:[UIFont fontWithName:kFutura size:15] color:[UIColor colorWithHexString:@"#FFFFFF"]];
    termLab.frame = CGRectMake(rateLab.right + 10, rateLab.top, 160, DimensionBaseIphone6(18));
    [midImgV addSubview:termLab];
    termLab.text = esString(self.cardModel.objective);
    
    UILabel *termLabDesc = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#75FA8D"]];
    termLabDesc.frame = CGRectMake(termLab.left, rateLabDesc.top, 160, DimensionBaseIphone6(16));
    [midImgV addSubview:termLabDesc];
    termLabDesc.text = ASLocalizedString(@"home3Str");
    
    midImgV.userInteractionEnabled = YES;

    UIButton *loanBtn = [[UIButton alloc] initWithFrame:CGRectMake((midImgV.width - 235)/2, termLabDesc.bottom +  DimensionBaseIphone6(20), 235, DimensionBaseIphone6(48))];
    loanBtn.backgroundColor = [UIColor colorWithHexString:@"#75FA8D"];
    loanBtn.layer.cornerRadius = DimensionBaseIphone6(24);
    loanBtn.layer.masksToBounds = YES;
    [midImgV addSubview:loanBtn];
    [loanBtn setTitle:ASLocalizedString(@"home4Str") forState:UIControlStateNormal];
    [loanBtn setTitle:ASLocalizedString(@"home4Str") forState:UIControlStateSelected];
    [loanBtn setTitle:ASLocalizedString(@"home4Str") forState:UIControlStateHighlighted];
    [loanBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [loanBtn setTitleColor:kBlackColor forState:UIControlStateSelected];
    [loanBtn setTitleColor:kBlackColor forState:UIControlStateHighlighted];
    [loanBtn setImage:[UIImage imageNamed:@"icon_home5"] forState:UIControlStateNormal];
    [loanBtn setImage:[UIImage imageNamed:@"icon_home5"] forState:UIControlStateSelected];
    [loanBtn setImage:[UIImage imageNamed:@"icon_home5"] forState:UIControlStateHighlighted];
    loanBtn.titleLabel.font = [UIFont fontWithName:kFutura size:15];
    
    [loanBtn setImgRightTitltLeft:10];
    
    [loanBtn addTarget:self action:@selector(clickLoan) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)clickLoan{
    [self enterOrderDetail:esString(self.cardModel.slender)];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.isNetworkError) {
        return 1;
    }
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isNetworkError) {
        return 1;
    }
    id value = [self.data[section] valueForKey:@"value"];
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeListTableCell class]){
        if (isArray(value)) {
            NSArray * datas = (NSArray *)value;
            return datas.count;
        }
        else{
            return 0;
        }
    }
    
    return 1;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isNetworkError) {
        UIImage *img = [UIImage imageNamed:@"icon_empty"];
        return 140 + img.size.height + 5 + 5 +36 + 20 + 60;
    }
    if (self.data.count == 0) {
        return 0.0001f;
    }
    
    NSDictionary * dataDictionary = self.data[indexPath.section];
    Class cellClass = dataDictionary[@"class"];
    
    if (cellClass == [HomeThreeBtnTableCell class]){
        return 82;
    }
    else if (cellClass == [HomeBannerTableCell class]){
        UIImage *img = [UIImage imageNamed:@"icon_home8"];
        return DimensionBaseIphone6(img.size.height);
    }
    else if (cellClass == [HomeQuicklyWayTableCell class]){
        return 146;
    }
    else if (cellClass == [HomeContactServiceTableCell class]){
        return 88;
    }
    else if (cellClass == [HomeRepaymentTableCell class]){
        return 60;
    }
    else if (cellClass == [HomeListTableCell class]){
        return 126;
    }
    return 0.0001f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isNetworkError) {
        EmptyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kErrorNetCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNetError = YES;
        cell.clickBtnBlock = ^{
            [[DKCore sharedDKCore] showNetErrorAlertView];
        };
        return cell;
    }
    
    
    NSDictionary * dataDictionary = self.data[indexPath.section];
    Class cellClass = dataDictionary[@"class"];
    
    if (cellClass == [HomeThreeBtnTableCell class]){
        return [self getThreeBtnCellIndexPath:indexPath];
    }
    else if (cellClass == [HomeBannerTableCell class]){
        return [self getBannerCellIndexPath:indexPath];
    }
    else if (cellClass == [HomeQuicklyWayTableCell class]){
        return [self getQuicklyCellIndexPath:indexPath];
    }
    else if (cellClass == [HomeContactServiceTableCell class]){
        return [self getServiceCellIndexPath:indexPath];
    }
    else if (cellClass == [HomeRepaymentTableCell class]){
        return [self getRepayCellIndexPath:indexPath];
    }
    else if (cellClass == [HomeListTableCell class]){
        return [self getListCellIndexPath:indexPath];
    }
    return nil;
}


- (UITableViewCell *)getThreeBtnCellIndexPath:(NSIndexPath *)indexPath{
    HomeThreeBtnTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kHomeThreeBtnCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.icon1.image = [UIImage imageNamed:@"icon_home9"];
    cell.icon2.image = [UIImage imageNamed:@"icon_home10"];
    cell.icon3.image = [UIImage imageNamed:@"icon_home11"];
    cell.lab1.text = @"Loan";
    cell.lab2.text = @"Repayment";
    cell.lab3.text = @"Questionnaire";
    cell.clickBtnBlock = ^(NSInteger tag) {
        if (tag == 1) {
            [self enterOrderDetail:esString(self.cardModel.slender)];
        }
        else if (tag == 2) {
            [self judgeLocation];
            
            [CurrentUser actionWhenLogin:^{
                [self.tabBarController setSelectedIndex:[CurrentUser mine].isYNLanguage ? 1 : 2];
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":[CurrentUser mine].isYNLanguage ? @"2":@"3"}];
            }];
            
        }
        else if (tag == 3) {
            [self judgeLocation];
            [CurrentUser actionWhenLogin:^{
                QuestionListViewController *vc = [[QuestionListViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }];
            
            
        }
    };
    return cell;
}

- (UITableViewCell *)getBannerCellIndexPath:(NSIndexPath *)indexPath{
    HomeBannerTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kHomeBannerCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell reloadData:self.bannerArr];
    return cell;
}

- (UITableViewCell *)getQuicklyCellIndexPath:(NSIndexPath *)indexPath{
    HomeQuicklyWayTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kHomeQuicklyCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.icon.image = [UIImage imageNamed:@"icon_home6"];
    if ([CurrentUser mine].isYNLanguage) {
        cell.icon.image = [UIImage imageNamed:@"icon_home6-yn"];
    }

    cell.clickIconBlock = ^{
       
    };
    return cell;
}

- (UITableViewCell *)getServiceCellIndexPath:(NSIndexPath *)indexPath{
    HomeContactServiceTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kHomeServiceCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.icon.image = [UIImage imageNamed:@"icon_home7"];
    if ([CurrentUser mine].isYNLanguage) {
        cell.icon.image = [UIImage imageNamed:@"icon_home7-yn"];
    }

    cell.clickIconBlock = ^{
        [self judgeLocation];
        [CurrentUser actionWhenLogin:^{
            if ([[[NSUserDefaults standardUserDefaults] valueForKey:kIsNeedLocation] integerValue] == 1) {
                if (![AuthorHelper determineWhetherTheAPPOpensTheLocation]) {
                    return;
                }
            }
            
            [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(self.hModel.preceded.justified)];
        }];
        
    };
    return cell;
}

- (UITableViewCell *)getRepayCellIndexPath:(NSIndexPath *)indexPath{
    HomeRepaymentTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kHomeRepayCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.repayArr.count > 0) {
    
        [cell reloadData:self.repayArr];

        cell.callBackBannerReplyBlock = ^(NSString * _Nonnull urlStr) {
            
            [self judgeLocation];
            
            [CurrentUser actionWhenLogin:^{
                
                if ([[[NSUserDefaults standardUserDefaults] valueForKey:kIsNeedLocation] integerValue] == 1) {
                    if (![AuthorHelper determineWhetherTheAPPOpensTheLocation]) {
                        return;
                    }
                }
                
               
                [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(urlStr)];
            }];
        };
       
    }
    

    return cell;
}

- (UITableViewCell *)getListCellIndexPath:(NSIndexPath *)indexPath{
    HomeListTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kHomeListCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.listArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.isNetworkError || self.data.count == 0) {
        return;
    }
    
    NSDictionary *dataDictionary = self.data[indexPath.section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeListTableCell class]){
        HomeListTableCell *selCell = [tableView cellForRowAtIndexPath:indexPath];
        ProductListModel *mm = selCell.model;
        
        [self enterOrderDetail:esString(mm.slender)];
        
    }
     
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *secHeaderView = [[UIView alloc] init];
    secHeaderView.backgroundColor = [UIColor clearColor];
    if (self.isNetworkError) {
        return secHeaderView;
    }
    
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeListTableCell class]){

        UIView *backV = [[UIView alloc] initWithFrame:CGRectMake(15, 20, kScreenWidth - 30, 31)];
        backV.backgroundColor = [UIColor whiteColor];
        backV.layer.mask = [NSString UIBezierPathWithRect:backV.bounds withCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadiu:CGSizeMake(14, 14)];
        [secHeaderView addSubview:backV];
        
        UILabel *lab = [UILabel createLabel:[UIFont fontWithName:kFuturaBold size:14] color:kBlackColor];
        lab.text = ASLocalizedString(@"Recommended For You");
        [backV addSubview:lab];
        lab.frame = CGRectMake(15, 10, kScreenWidth, 21);
    }
   
    return secHeaderView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.isNetworkError || self.data.count == 0) {
        return 0.01f;
    }
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeListTableCell class]){
        return 51;
    }
     
    return 20.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *secFooterView = [[UIView alloc] init];
    secFooterView.backgroundColor = [UIColor clearColor];
    if (self.isNetworkError || self.data.count == 0) {
        return secFooterView;
    }
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeListTableCell class]){
        UIView *backV = [[UIView alloc] initWithFrame:CGRectMake(15, 0, kScreenWidth - 30, 20)];
        backV.backgroundColor = [UIColor whiteColor];
        backV.layer.mask = [NSString UIBezierPathWithRect:backV.bounds withCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight withRadiu:CGSizeMake(14, 14)];
        [secFooterView addSubview:backV];
    }
     
    
    return secFooterView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.isNetworkError || self.data.count == 0) {
        return 0.01f;
    }
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeListTableCell class]){
        return 20;
    }
     
    
    return 0.01f;
}


- (void)judgeLocation{
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [[DKCore sharedDKCore] initLocation];
        return;
    }
    
    
}
#pragma mark ---enterOrderDetail
- (void)enterOrderDetail:(NSString *)idStr{
    
    [self judgeLocation];
    
    [CurrentUser actionWhenLogin:^{
       
        if ([[[NSUserDefaults standardUserDefaults] valueForKey:kIsNeedLocation] integerValue] == 1) {
            if (![AuthorHelper determineWhetherTheAPPOpensTheLocation]) {
                return;
            }
        }
        
        [DKCore sharedDKCore].isNeedUploadLocation = YES;
        [[DKCore sharedDKCore] initLocation];
        
        [DataCategoryUpload uploadDataDeviceInfo];
        
        NSString *startTimeStr = [[NSUserDefaults standardUserDefaults] valueForKey:kRecordLoginStartTime];
        NSString *endTimeStr = [[NSUserDefaults standardUserDefaults] valueForKey:kRecordLoginEndTime];
        
        if (!PMStringIsEmpty(startTimeStr) && !PMStringIsEmpty(endTimeStr)) {
            [self uploadMaiDianLoginData];
        }
        
    
        [BoxLoadingHelper showBoxLoadingWithMessage:@""];
        NSMutableDictionary *muDic = @{
            @"largely":esString(idStr),
            @"truces":@"1001",
            @"exists":@"1000",
            @"enmity":@"1000",
            @"interior":@"interiorApply"
        }.mutableCopy;
        [HttpNetHelper postNetworkHelperForPath:kApplyUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
            [BoxLoadingHelper hideBoxLoading];
            if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                return;
            }
            
            NSDictionary *dic = responseDic[@"clip"];
            
            if (!PMObjectIsEmpty(dic[@"ways"])) {
             
                NSDictionary *dcDic = dic[@"ways"];
                [self initDCAlertView:dcDic];
            } else {
               
                if (!PMStringIsEmpty(dic[@"twentieth"])) {
                    [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(dic[@"twentieth"])];
                } else {
                    OrderDetailViewController *vc = [[OrderDetailViewController alloc] init];
                    vc.idStr = esString(idStr);
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
            
            
        } onCompleteFailur:^(NSError * _Nonnull error) {
            [BoxLoadingHelper hideBoxLoading];
        } withIsForm:YES];
        
        
        
    }];
    
}


- (void)initDCAlertView:(NSDictionary *)dic{
    
    NSArray *btnArr = dic[@"seek"];
    
    NSDictionary *dic1 = btnArr.firstObject;
    NSString *str1 = esString(dic1[@"massacres"]);
    NSString *str1Url = esString(dic1[@"twentieth"]);
    
    NSDictionary *dic2 = btnArr.lastObject;
    NSString *str2 = esString(dic2[@"massacres"]);
    NSString *str2Url = esString(dic2[@"twentieth"]);
    
    AlertDCView *dcV = [[AlertDCView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:esString(dic[@"arrow"]) withDescStr:esString(dic[@"shin"]) withCancelStr:str2 withSureStr:str1 withIsDC:YES];
    [[UIApplication sharedApplication].keyWindow addSubview:dcV];
    dcV.clickCancelBlock = ^{
       
        [[DKCore sharedDKCore] jumpToControllerWithUrlString:str2Url];
    };
    dcV.clickSureBlock = ^{
       
        [[DKCore sharedDKCore] jumpToControllerWithUrlString:str1Url];
    };
}
   
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.isNetworkError) {
        return;
    }
    
    CGFloat offset_Y = scrollView.contentOffset.y;
   
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
    }
    else{
        if (self.isOffsetY) {
            self.isOffsetY = NO;
            [self loadData];
        }
    }
}

#pragma mark ----- uploadMaiDianLoginData -------
- (void)uploadMaiDianLoginData{
    self.timeInt = 0;
    self.isLocationSuccess = NO;
    [self initLocation];
}

- (void)initLocation{
    self.maiDianTimer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.maiDianTimer forMode:NSRunLoopCommonModes];
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)addTimer{
    self.timeInt ++;
    if (self.isLocationSuccess) {
        [self.maiDianTimer invalidate];
        self.maiDianTimer = nil;
        self.timeInt = 0;
    }
    else{
        if (self.timeInt > 8) {
            [self.maiDianTimer invalidate];
            self.maiDianTimer = nil;
            self.timeInt = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServerWithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
            
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *newlocation = locations[0];
    NSString *longitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude];
    NSString *latitudeStr =  [NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude];
    [self.locationManager stopUpdatingLocation];
    
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.isLocationSuccess = YES;
    
    if (self.timeInt <= 8) {
        [self goServerWithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
    }
}

- (void)goServerWithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{
    NSString *startTimeStr = [[NSUserDefaults standardUserDefaults] valueForKey:kRecordLoginStartTime];
    NSString *endTimeStr = [[NSUserDefaults standardUserDefaults] valueForKey:kRecordLoginEndTime];
    [DataCategoryUpload uploadMaiDianData:@"1" withOrderIdStr:@"" withOrderNoStr:@"" withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:startTimeStr withEndTime:endTimeStr];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}


@end
